import { useState, useRef } from 'react'

import './PictureCard.less'


interface PictureCardProps {
    word: string
    submit: (data: string) => void
    audio: string
}


export default function PictureCard({ word, submit, audio }: PictureCardProps) {

    const [imgPreview, setImgPreview] = useState('https://res.bearbobo.com/resource/upload/W44yyxvl/upload-ih56twxirei.png')
    const audioURL = audio
    const audioRef = useRef<any>(null)
    function playAudio() {
        if (audioRef.current) {
            audioRef.current.src = audioURL
            audioRef.current.play()
        }
    }

    return (
        <div className='picture-card'>
            <input id='selectImage' type="file" className='input'
                onChange={(e) => {
                    if (e.target.files && e.target.files[0]) {
                        console.log(e.target.files);
                        // setImgPreview(URL.createObjectURL(e.target.files[0]));
                        return new Promise((resolve, reject) => {
                            // 将本地的图片转换为base64编码
                            const render = new FileReader()
                            if (e.target.files && e.target.files[0]) {
                                render.readAsDataURL(e.target.files[0])
                            }
                            // 读取完成
                            render.onload = () => {
                                setImgPreview(render.result as string)
                                submit(render.result as string)
                                resolve(render.result)
                            }
                            // 读取失败
                            render.onerror = (error) => {
                                console.log('读取失败');
                                reject(error)
                            }

                        })
                    }
                }} />
            <label htmlFor="selectImage" className='upload'>
                <img src={imgPreview} alt="" className='picture-card-img' />
            </label>
            <div className='word'>
                {word}
            </div>
            <div className='palyAudio' onClick={() => playAudio()}>

                <img width={20} src="https://res.bearbobo.com/resource/upload/Omq2HFs8/playA-3iob5qyckpa.png" alt="" />
            </div>
            <audio ref={audioRef}></audio>
        </div>
    )
}
